package com.tanqing.ddd.web.exception;

import cn.hutool.core.util.ObjectUtil;
import com.tanqing.ddd.domain.domain.DomainException;
import com.tanqing.ddd.domain.domain.NotRollbackException;
import com.tanqing.ddd.web.bean.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({DomainException.class})
    public Result<Object> exceptionHandler(DomainException e) {
        log.error("DomainException:{}", e);
        String failMsg = e.getMessage();
        String code = e.getCode();
        if (ObjectUtil.isEmpty(code)) {
            code = "501";
        }

        return Result.<Object>create().fail(code, failMsg);
    }

    @ExceptionHandler({NotRollbackException.class})
    public Result<Object> exceptionHandler(NotRollbackException e) {
        log.error("NotRollbackException:{}", e);
        String failMsg = e.getMessage();
        String code = e.getCode();
        if (ObjectUtil.isEmpty(code)) {
            code = "501";
        }

        return Result.<Object>create().fail(code, failMsg);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<Object> handleValidException(MethodArgumentNotValidException e) {
        return Result.<Object>create().fail("502", e.getBindingResult().getFieldError().getDefaultMessage());
    }
}